package com.tianhui.consignortwofei.pattern.orderOprate.impl;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.text.TextUtils;

import androidx.fragment.app.FragmentActivity;

import com.fgs.common.permission.OnPermissionCheckResult;
import com.fgs.common.permission.PermissionHelper;
import com.fgs.common.utils.ToastUtil;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.model.enty.OrderInfo;
import com.tianhui.consignortwofei.mvp.model.enty.OrderOperateInfo;
import com.tianhui.consignortwofei.pattern.orderOprate.IOrderOperate;
import com.tianhui.consignortwofei.utils.Util;
import com.tianhui.consignortwofei.widget.OrderShareDialog;
import com.tianhui.consignortwofei.widget.QRCodeDialog;
import com.xuexiang.xaop.annotation.IOThread;
import com.xuexiang.xaop.enums.ThreadType;
import com.xuexiang.xqrcode.XQRCode;
import com.xuexiang.xui.widget.dialog.bottomsheet.BottomSheet;
import com.xuexiang.xui.widget.dialog.bottomsheet.BottomSheetItemView;
import com.xuexiang.xutil.display.ImageUtils;
import com.xuexiang.xutil.security.Base64Utils;

import java.util.List;

/**
 * @author fgs
 * @date 2020/9/27
 * @description 分享订单
 **/
public class ShareOrderOperate implements IOrderOperate {
    private static final int THUMB_SIZE = 150;
    private OrderShareDialog orderShareDialog;
    private int mTargetScene = SendMessageToWX.Req.WXSceneSession;
    private IWXAPI api;
    private String shareContent;

    @Override
    public void orderOperate(Context context, OrderOperateInfo operateInfo) {

        if (operateInfo != null && operateInfo.orderInfo != null) {
            shareContent = getShareContent(operateInfo.orderInfo);
//            api = WXAPIFactory.createWXAPI(context, PlatformConfig.WE_CHAT_APP_ID, false);
//            showSimpleBottomSheetGrid(context, operateInfo);
            showCopyDialog(context);
        } else {
            ToastUtil.showShortToast("分享失败");
        }

    }

    private void showSimpleBottomSheetGrid(Context context, OrderOperateInfo operateInfo) {
        final int TAG_SHARE_WECHAT_TEXT = 0;
        final int TAG_SHARE_WECHAT_QRCODE = 1;
        final int TAG_COPY_TEXT = 2;
        final int TAG_SAVE_CORD = 3;
        BottomSheet.BottomGridSheetBuilder builder = new BottomSheet.BottomGridSheetBuilder(context);
        builder
                .addItem(R.mipmap.icon_more_operation_share_friend, "分享文字", TAG_SHARE_WECHAT_TEXT, BottomSheet.BottomGridSheetBuilder.FIRST_LINE)
                .addItem(R.mipmap.icon_more_operation_share_friend, "分享二维码", TAG_SHARE_WECHAT_QRCODE, BottomSheet.BottomGridSheetBuilder.FIRST_LINE)
                .addItem(R.mipmap.icon_share_text, "复制文字", TAG_COPY_TEXT, BottomSheet.BottomGridSheetBuilder.FIRST_LINE)
                .addItem(R.mipmap.icon_qr_code, "保存二维码", TAG_SAVE_CORD, BottomSheet.BottomGridSheetBuilder.FIRST_LINE)
                .setOnSheetItemClickListener(new BottomSheet.BottomGridSheetBuilder.OnSheetItemClickListener() {
                    @Override
                    public void onClick(BottomSheet dialog, BottomSheetItemView itemView) {
                        dialog.dismiss();
                        int tag = (int) itemView.getTag();
                        switch (tag) {
                            case TAG_SHARE_WECHAT_TEXT:
                                if (isInstallWeChat(context)) {
                                    shareOrderText(shareContent);
                                } else {
                                    ToastUtil.showShortToast("手机中未安装微信");
                                }
                                break;
                            case TAG_SHARE_WECHAT_QRCODE:
                                if (isInstallWeChat(context)) {
                                    Bitmap bitmap = createQRCodeWithLogo(operateInfo.orderInfo.billno, ImageUtils.getBitmap(R.mipmap.icon_app));
                                    shareOrderQRCord(bitmap);
                                } else {
                                    ToastUtil.showShortToast("手机中未安装微信");
                                }
                                break;
                            case TAG_COPY_TEXT:
                                showCopyDialog(context);
                                break;
                            case TAG_SAVE_CORD:
                                new PermissionHelper().checkPermissions((FragmentActivity) context, new OnPermissionCheckResult() {
                                    @Override
                                    public void grantedResult() {
                                        Bitmap bitmap = createQRCodeWithLogo(operateInfo.orderInfo.billno, ImageUtils.getBitmap(R.mipmap.icon_app));
                                        new QRCodeDialog(context, bitmap).show();
                                    }

                                    @Override
                                    public void shouldShowRequestPermissionRationale() {

                                    }

                                    @Override
                                    public void grantedForbidResult() {

                                    }
                                }, Manifest.permission.WRITE_EXTERNAL_STORAGE);

                                break;
                        }

                    }
                }).build().show();


    }

    private void showCopyDialog(Context context) {
        if (orderShareDialog == null) {
            orderShareDialog = new OrderShareDialog(context, shareContent);
        }
        orderShareDialog.show();
    }

    /**
     * 生成简单的带logo的二维码
     *
     * @param content
     * @param logo
     */
    @IOThread(ThreadType.Single)
    private Bitmap createQRCodeWithLogo(String content, Bitmap logo) {
        Bitmap bitmap = XQRCode.createQRCodeWithLogo(content, 400, 400, logo);
        return bitmap;
    }

    private void shareOrderQRCord(Bitmap bitmap) {
        Bitmap bmp = bitmap;
        //初始化 WXImageObject 和 WXMediaMessage 对象
        WXImageObject imgObj = new WXImageObject(bmp);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

        //设置缩略图
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        bmp.recycle();
        msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        req.scene = mTargetScene;
//        req.userOpenId = getOpenId();
        //调用api接口，发送数据到微信
        api.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    private void shareOrderText(String text) {
        WXTextObject textObj = new WXTextObject();
        textObj.text = text;

        //用 WXTextObject 对象初始化一个 WXMediaMessage 对象
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = textObj;
        msg.description = text;

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("text");
        req.message = msg;
        req.scene = mTargetScene;
        //调用api接口，发送数据到微信
        api.sendReq(req);
    }

    private String getShareContent(OrderInfo orderInfo) {
        String consignor = SharedPreferenceManager.getInstance().getConsignorName();
        String startAddress = orderInfo.deliverprovince + orderInfo.delivercity + orderInfo.delivercounty + orderInfo.deliverdetails;
        String endAddress = orderInfo.destinationprovince + orderInfo.destinationcity + orderInfo.destinationcounty + orderInfo.destinationdetails;

        String base64Number = "";
        if (orderInfo != null && !TextUtils.isEmpty(orderInfo.billno)) {

            String billNo = orderInfo.billno;
            base64Number = Base64Utils.encode(billNo);
            if (base64Number.contains("=") && !base64Number.contains("==")) {
                base64Number += "=";
            } else if (!base64Number.contains("==")) {
                base64Number += "==";
            }
        }

        StringBuilder content = new StringBuilder();
        content.append("幅治这行话打开皓俊通网络货运服务系统APP");
        content.append("&&");
        content.append(base64Number);
        content.append("接收");
        content.append("「「「");
        content.append(consignor);
        content.append("」」");
        content.append(startAddress);
        content.append("至");
        content.append(endAddress);
        content.append("（" + orderInfo.weight + "）吨");
        content.append("的订单");
        return content.toString();
    }


    private boolean isInstallWeChat(Context context) {

        if (api.isWXAppInstalled()) {
            return true;
        } else {
            final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
            List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
            if (pinfo != null) {
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    if (pn.equalsIgnoreCase("com.tencent.mm")) {
                        return true;
                    }
                }
            }
            return false;
        }
    }
}
